/* © 2010 Stephan Reichholf <stephan at reichholf dot net>
 * 
 * Licensed under the Create-Commons Attribution-Noncommercial-Share Alike 3.0 Unported
 * http://creativecommons.org/licenses/by-nc-sa/3.0/
 */

package com.example.dreammain;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.example.helpers.ExtendedHashMap;
import com.example.helpers.URIStore;

import android.app.ListActivity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author bugcheck
 *
 */
public class DreamActivity extends ListActivity
{
	private final static String  TAG   = "DREAM";
    private final static String  IMAGE_EXTENSION = ".png";
    
    private Toast mToast;
    private long  mLastBackPressTime = 0;
    
    private boolean mPickMode;
    
    private ServiceListTask mServiceListTask;
    
	@Override
    public void onCreate(Bundle savedInstanceState)
	{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try
        {
            String[] titles = getResources().getStringArray(R.array.titles_array);
            List<String> al = new ArrayList<String>();
            for(int i=0;i<titles.length;i++)
                al.add(titles[i]);

            CustomAdapter ca = new CustomAdapter(this, R.layout.list_item, al);
            setListAdapter(ca);

            ListView lv = getListView();
            lv.setOnItemClickListener(new OnItemClickListener()
            {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id)
                {
                }
            });
        }
        catch (Exception e)
        {
            Log.d(TAG, "Exception in onCreate(): "+e.getLocalizedMessage());
        }
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("context", "this"));
        mServiceListTask = new ServiceListTask();
        mServiceListTask.execute(params);
    }
	
	@Override
    public void onBackPressed()
	{
		if ( mLastBackPressTime < (System.currentTimeMillis() - (long)3000))
		{
            mToast = Toast.makeText(this, "Press back again to close the app", 4000);
            mToast.show();
            mLastBackPressTime = System.currentTimeMillis();
        }
		else
		{
            if (mToast != null)
            {
                mToast.cancel();
            }
            super.onBackPressed();
        }
    }
	
	protected class ServiceListTask extends AsyncTask<ArrayList<NameValuePair>, String, Boolean>
	{
		protected ArrayList<ExtendedHashMap> mTaskList;
		private boolean mIsBouquetList;
		
		public ServiceListTask()
		{
		}
		
		@Override
		protected Boolean doInBackground(ArrayList<NameValuePair>... params)
		{
			/*mTaskList = new ArrayList<ExtendedHashMap>();
			if (isCancelled())
				return false;
			publishProgress(getString(R.string.fetching_data));

			String xml;
			AbstractListRequestHandler handler;
			if (mIsBouquetList || mPickMode) {
				handler = new ServiceListRequestHandler();
			} else {
				if (DreamDroid.featureNowNext())
					handler = new EpgNowNextListRequestHandler();
				else
					handler = new EventListRequestHandler(URIStore.EPG_NOW);
			}
			xml = handler.getList(getHttpClient(), params[0]);

			if (xml != null && !isCancelled()) {
				publishProgress(getString(R.string.parsing));
				boolean result = false;
				result = handler.parseList(xml, mTaskList);
				return result;

			}*/
			return false;
		}

		@Override
		protected void onProgressUpdate(String... progress)
		{
		}
		
		@Override
		protected void onPostExecute(Boolean result)
		{
		}
	}
	
	public static class CustomAdapter extends ArrayAdapter<String>
	{
        private static LayoutInflater mInflater;
        private static List<String>   mItems;
        private static int            mTextViewResourceId;
        private static Context        mContext;

        public CustomAdapter(DreamActivity context, int textViewResourceId, List<String> items)
        {
            super(context, textViewResourceId, items);
            
            mContext = context;
            
            if(textViewResourceId == 0)
            {
                mTextViewResourceId = R.layout.list_item;
            }
            else
            {
                mTextViewResourceId = textViewResourceId;
            }
            mItems = items;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ViewHolder holder;

            if (convertView == null)
            {
                convertView = mInflater.inflate(mTextViewResourceId, null);
                holder = new ViewHolder();
                holder.text = (TextView)  convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.img);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }
            
            holder.text.setText(mItems.get(position) );
            String filename = position + IMAGE_EXTENSION;
            try
            {
                Bitmap bm = getBitmapFromAsset(filename);
                if (bm != null)
                {
                    holder.icon.setVisibility(View.VISIBLE);
                    holder.icon.setImageBitmap(bm);
                }
                else
                {
                }
            }
            catch(IOException ioe)
            {
                holder.icon.setVisibility(View.GONE);
            }
            
            return convertView;
        }

        private static Bitmap getBitmapFromAsset(String strName) throws IOException
        {
            AssetManager assetManager = mContext.getAssets();
            InputStream istr = assetManager.open(strName);
            Bitmap bitmap = BitmapFactory.decodeStream(istr);
            istr.close();
            return bitmap;
        }

        static class ViewHolder
        {
            TextView text;
            ImageView icon;
        }
    }
}